package concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平锁和非公平锁体现在别人释放锁的一瞬间，如果前面已经有排队的，新来的是否可以插队，如果可以插队表示是非公平的，
 * 如果不可用插队，只能排在最后面，是公平的方式
 *
 * @author jack.wu
 * @since 2019/12/25 10:13
 */
public class ReentrantLockDemo {

    /**
     *
     */
    static class Demo {

        public static void main(String[] args) throws InterruptedException {
            // 非公平锁
//            lock(false);
            TimeUnit.SECONDS.sleep(3);
            System.out.println("---------------");
            // 公平锁
            lock(true);
        }

        private static void lock(boolean fair) throws InterruptedException {
            ReentrantLock lock = new ReentrantLock(fair);
            Thread t1 = new Thread(() -> {
                lock.lock();
                try {
                    TimeUnit.SECONDS.sleep(3);
                    new Thread(() -> {
                        m1(lock, "son");
                    }).start();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            });
            t1.setName("t1");
            t1.start();
            TimeUnit.SECONDS.sleep(1);
            m1(lock, "father");
        }

        private static void m1(ReentrantLock lock, String type) {
            for (int i = 0; i < 10; i++) {
                Thread thread = new Thread(() -> {
                    lock.lock();
                    try {
                        System.out.println(type+"获取到锁");
                    } finally {
                        lock.unlock();
                    }
                });
                thread.setName(type + " - " + i);
                thread.start();
            }
        }
    }

}
